package com.cqcet.wenchuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqcet.wenchuang.entity.Admin;
import com.cqcet.wenchuang.entity.LoginAdmin;
import com.cqcet.wenchuang.entity.LoginUser;
import com.cqcet.wenchuang.entity.User;
import com.cqcet.wenchuang.mapper.AdminMapper;
import com.cqcet.wenchuang.mapper.MenuMapper;
import com.cqcet.wenchuang.mapper.UserMapper;
import com.cqcet.wenchuang.service.LoginService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class LoginServiceImpl implements LoginService, UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 身份验证，获取权限，商家管理员用户公用
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //用户登录
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(user)) {
            //设置权限
            List<String> permissionKeyList = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user, permissionKeyList);
        }
        //管理员商家登录
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(adminLambdaQueryWrapper);
        //两种身份都登录失败
        if (ObjectUtils.isEmpty(admin)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //设置权限
        List<String> permissionKeyList = menuMapper.selectPermsByAdminId(admin.getId());
        return new LoginAdmin(admin, permissionKeyList);
    }
}